﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using LitJson;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;

public class KnapsackManager : MonoBehaviour
{
	private static KnapsackManager _instance;
	public static KnapsackManager GetInstance
	{
		get
		{
			if (_instance == null)
			{
				_instance = GameObject.Find("Camera").GetComponent<KnapsackManager>();
			}

			return _instance;
		}
	}

	private bool isShowToolTilePanel = false;

	public GameObject pickGood;
	public GoodUI GetPickGoodUI
	{
		get
		{
			return pickGood.GetComponent<GoodUI>();
		}
	}

	public Vector3 GetPickGoodLocalPos
	{
		get
		{
			return pickGood.transform.localPosition;
		}
	}
	
	public bool isPickGood = false;

	/// <summary>
	/// 存储多个物品对象（从json解析过来）
	/// </summary>
	private List<KnapsackGood> goodList;
    void Awake()
    {
        ParseGoodsJson();
    }

	private GameObject toolTilePanel;
	private GameObject canvase;
	// Use this for initialization
	void Start () 
    {
		toolTilePanel = GameObject.Find("ToolTilePanel");
		canvase = GameObject.Find("Canvas");
		pickGood = GameObject.Find("PickGoodUI");
	}
	
	// Update is called once per frame
	void Update () 
    {
		if (isPickGood)
		{
			Vector2 point = Vector2.zero;
			//该函数是将屏幕坐标转化以第一个参数对象的子节点坐标
			//参数一：需要转换的坐标以该对象作为父节点
			//参数二：鼠标点
			//参数三：参数一对象以哪个摄像机渲染（由于该参数一画布没有相机渲染，故为null）
			//参数四：返回一个需要转换的目标点
			RectTransformUtility.ScreenPointToLocalPointInRectangle(canvase.GetComponent<Canvas>().transform as RectTransform, Input.mousePosition, null, out point);
			pickGood.GetComponent<GoodUI>().SetLocalPosition(point);
		}
		if (isShowToolTilePanel)
		{
			Vector2 point=Vector2.zero;
			//该函数是将屏幕坐标转化以第一个参数对象的子节点坐标
			//参数一：需要转换的坐标以该对象作为父节点
			//参数二：鼠标点
			//参数三：参数一对象以哪个摄像机渲染（由于该参数一画布没有相机渲染，故为null）
			//参数四：返回一个需要转换的目标点
			RectTransformUtility.ScreenPointToLocalPointInRectangle(canvase.GetComponent<Canvas>().transform as RectTransform,Input.mousePosition,null, out point);
			toolTilePanel.GetComponent<ToolTilePanel>().SetLocalPosition(point + new Vector2(5,-15));
		}
        //                 画布的EventSystem事件上    判断点击鼠标左键位置上是否有UI对象
        //                                  |                        |
        //UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(-1))
        if(isPickGood&&Input.GetMouseButtonDown(0)&&UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(-1)==false)
        {
            isPickGood = false;
            GetPickGoodUI.SetLocalPosition(new Vector3(-420, 2, 0));

            HideToolTilePanel();
        }
	}

	
	void ParseGoodsJson()
    {
		goodList = new List<KnapsackGood>();

        string path = Application.streamingAssetsPath + "/GoodJson.json";

		#region 文件流方式读文件
		/*
        byte[] bt=new byte[1024];
        char[] data=new char[1024];
        

        FileStream fileStream = File.Open(path,FileMode.Open);
        fileStream.Seek(0,SeekOrigin.Begin);
        fileStream.Read(bt,0,1024);

        System.Text.Decoder coder = System.Text.Encoding.UTF8.GetDecoder();
        coder.GetChars(bt,0,bt.Length,data,0);

        Debug.Log(new string(data));

        fileStream.Flush();
        fileStream.Close();


		List<Consumable> goods = JsonMapper.ToObject<List<Consumable>>(new string(data));
		foreach (Consumable good in goods)
		{
			Debug.Log(good.ToString());
		}
		*/
		#endregion

		StreamReader sr =new StreamReader(path);
		string json=sr.ReadToEnd();
		sr.Close();

		JsonData data = JsonMapper.ToObject(json);
		int i = 0;
		for (i = 0; i <= data.Count - 1; i++)
		{
			BaseProperty gp = JsonMapper.ToObject<BaseProperty>(data[i]["goodProperty"].ToJson());

			KnapsackGood kg = null;
			switch (gp.goodType)
			{
				case KnapsackGood.GoodType.Consumable:
					int HP = int.Parse(data[i]["HP"].ToString());
					int MP = int.Parse(data[i]["MP"].ToString());
					kg = new Consumable(HP,MP,gp);

					break;
				case KnapsackGood.GoodType.Equipment:
                    int strength = int.Parse(data[i]["strength"].ToString());
                    int intellect = int.Parse(data[i]["intellect"].ToString());
                    int agility = int.Parse(data[i]["agility"].ToString());
					int stamina = int.Parse(data[i]["stamina"].ToString());
                    Equipment.EquitmentType equitmentType = (Equipment.EquitmentType)System.Enum.Parse(typeof(Equipment.EquitmentType), data[i]["equitmentType"].ToString());
					kg = new Equipment(strength,intellect,agility,stamina,equitmentType,gp);

					break;
				case KnapsackGood.GoodType.Meterial:

					break;
				case KnapsackGood.GoodType.Weapon:
                    int damage = int.Parse(data[i]["damage"].ToString());
                    Weapon.WeaponType weaponType = (Weapon.WeaponType)System.Enum.Parse(typeof(Weapon.WeaponType), data[i]["weaponType"].ToString());
					kg = new Weapon(damage, weaponType, gp);

					break;
				default:
					break;
			}

			goodList.Add(kg);
		}
	}


	public KnapsackGood GetGoodWithID(int ID)
	{
		foreach (KnapsackGood good in goodList)
		{
			if (ID == good.goodProperty.ID)
			{
				return good;
			}
		}

		return null;
	}


	public void ShowToolTilePanel(string str=" ")
	{
		isShowToolTilePanel = true;
		toolTilePanel.GetComponent<ToolTilePanel>().ShowPanel(str);
	}

	public void HideToolTilePanel()
	{
		isShowToolTilePanel = false;
		toolTilePanel.GetComponent<ToolTilePanel>().HidePanel();
	}

}
